package controllers;

import models.Instructor;
import models.Student;
import play.data.validation.Email;
import play.data.validation.Required;
import play.data.validation.Validation;
import play.mvc.Controller;
import play.mvc.With;

@With (Secure.class)
public class Account extends Controller {
	/**
	 * index control panel
	 */
	public static void index() {
		controlPanel();
	}

	public static void controlPanel() {
		Object user = Security.getConnected();
		render(user);
	}

	public static void save(@Required (message = "You must enter an email") @Email (message = "You must enter a valid email") String email, String stEmail, String password, String password2, String stPassword, String stPassword2) {

		Object user = Security.getConnected();
		boolean pwdChange = false, stPwdChange = false;
		if (password != null && password.length() > 0) {
			pwdChange = true;
			if (!password.equals(password2)) {
				Validation.addError(password, "Passwords do not match");
			}
		}

		if (stPassword != null && stPassword.length() > 0) {
			stPwdChange = true;
			if (!stPassword.equals(stPassword2)) {
				Validation.addError(stPassword, "Student passwords do not match");
			}
		}

		if (user instanceof Instructor) {
			validation.required(stEmail);
			validation.email(stEmail);
		}

		if (Validation.hasErrors()) {
			Validation.keep();
			params.flash();
			controlPanel();
		}

		if (user instanceof Instructor) {
			Instructor instructor = (Instructor) user;
			instructor.email = email;
			instructor.studentAccount.email = stEmail;
			if (pwdChange) {
				instructor.pwd = Application.hash(password);
			}
			if (stPwdChange) {
				instructor.studentAccount.pwd = Application.hash(stPassword);
			}
			instructor.studentAccount.save();
			instructor.save();
		} else {
			Student student = (Student) user;
			student.email = email;
			if (pwdChange) {
				student.pwd = Application.hash(password);
			}
			student.save();
		}
		flash.success("Successfully saved your data");
		controlPanel();
	}
}
